package com.learn.algorithm_1_march;

/**
 * 179.最大数，https://leetcode-cn.com/problems/largest-number/
 *
 *      给定一组非负整数，重新排列它们的顺序使之组成一个最大的整数
 *      说明: 输出结果可能非常大，所以你需要返回一个字符串而不是整数。
 */
public class LargestNumber {

    public static void main(String[] args) {
        int[] nums = {3,30,34,5,9};
        System.out.println("比较result：" + new LargestNumber().force(nums));
    }

    /* 简单粗暴的双层遍历 */
    public String force(int[] nums) {
        //- 相邻两位正序、反序合并比较，判断是否互换
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (change(nums[i], nums[j])){
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        for (int num : nums) {
            builder.append(num);
        }
        //- "000" 返回 "0"
        if(builder.toString().startsWith("0")){
            return "0";
        } else{
            return builder.toString();
        }
    }

    public boolean change(int i, int j){
        String var1 = String.valueOf(i);
        String var2 = String.valueOf(j);
        return  !(Long.parseLong(var1 + var2) > Long.parseLong(var2 + var1));
    }

}
